<?php
namespace ac\modules\developer\controllers;

use Yii;
use ac\controllers\AuthController;
use app\modules\developer\models\AppInfo;
use app\modules\developer\models\AppPrice;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;
use common\behaviors\Sort;


class AppInfoController extends AuthController
{
    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

	/*APP信息列表*/
    public function actionAppInfoList()
    {
        $where = '';
        if(isset($this->get['display']) and $this->get['display'] == 2){
            $where = '{{%app_info}}.display = 2';
        }
        $appInfo = new AppInfo;
        $appInfoList = $appInfo::find()->where($where)->joinWith('category')
                       ->orderBy(['sort' => SORT_DESC])->asArray()->all();
        return Tool::showRes([0, '获取成功'], $appInfoList);
    }

    /*添加APP信息*/
    public function actionAddAppInfo()
    {
        if(Yii::$app->request->isPost){
            $appInfo = new AppInfo;
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                if(!$app_info_id = $appInfo->addAppInfo($this->post)){
                    $pass = false;
                    if($appInfo->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $appInfo->getErrors();//异常信息
                    }
                }
                if($pass and !empty($this->post['AppInfo']['app_year_limit'])){
                    $AppPrice = new AppPrice;
                    if(!$AppPrice->addAppPrice($this->post['AppInfo']['app_year_limit'], $app_info_id)){
                        $pass = false;
                        if($AppPrice->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $AppPrice->getErrors();//异常信息
                        }
                    }
                }

                if($pass){
                    $backInfo = [0, '添加应用成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();       
            };

        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    修改APP信息
    $flag               值为setDisplay时 作用是更改状态，为空是修改APP信息信息（更改APP信息状态的方法调用传参）
    $successBackInfo    成功的返回信息（更改APP信息状态的方法调用传参）
    */
    public function actionModifyAppInfo($flag = '', $successBackInfo = '')
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $id = isset($this->get['id'])?$this->get['id']:'';
            if($id){
                $appInfo = AppInfo::find()->joinWith('price')->where('{{%app_info}}.app_info_id = :id', [':id' => $id])->asArray()->one();
                if(!is_null($appInfo)){
                    if(!empty($appInfo['preview'])){
                        $appInfo['preview'] = explode(',', $appInfo['preview']);
                    }
                    // P($appInfo);
                    return Tool::showRes([0, '获取成功'], $appInfo);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $id = isset($this->post['AppInfo']['id'])?intval($this->post['AppInfo']['id']):'';
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $appInfo = new AppInfo;
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    if(!$appInfo->modifyAppInfo($this->post, $id, $flag)){
                        $pass = false;
                        if($appInfo->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $appInfo->getErrors();//异常信息
                        }
                    }

                    if($pass and !empty($this->post['AppInfo']['app_year_limit'])){
                        $AppPrice = new AppPrice;
                        $AppPrice->deleteAll('app_info_id = :id', [':id' => $id]);
                        if(!$AppPrice->addAppPrice($this->post['AppInfo']['app_year_limit'], $id)){
                            $pass = false;
                            if($AppPrice->hasErrors()){
                                $backInfo = ErrMap::getError(10005);//返回信息
                                $exception = $AppPrice->getErrors();//异常信息
                            }
                        }
                    }

                    if($pass){
                        if(empty($flag)){
                            $successBackInfo = '修改APP信息成功';//修改企业信息
                        }
                        $backInfo = [0, $successBackInfo];//返回信息
                        $transaction->commit();
                    }


                }catch(\Exception $exception){
                    $transaction->rollback();
                };

            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*是否显示1-不显示-2显示（是否显示操作）*/
    public function actionSetDisplay()
    {
        if(Yii::$app->request->isPost){
            return $this->actionModifyAppInfo('setDisplay', '设置APP信息状态成功');
        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*排序*/
    public function actionSetSort()
    {
        if(Yii::$app->request->isPost){
            $sort = $this->post['sort'];
            // P($sort);
            if(!empty($sort) and is_array($sort)){
                if($this->setSortList(new AppInfo, $sort)){
                    $backInfo = [0, '设置应用排序成功'];//返回信息
                }

            }
            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除APP信息,（真删除）*/
    public function actionDeleteAppInfo()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        if($id){
            $appInfo = new AppInfo;
            if($appInfo->deleteAll('app_info_id = :id', [':id' => $id])){//删除成功
                $AppPrice = new AppPrice;
                $AppPrice->deleteAll('app_info_id = :id', [':id' => $id]);
                $backInfo = [0, '删除APP信息成功'];//返回信息
            }else{//删除失败
                $backInfo = ErrMap::getError(10013, '删除APP信息失败');//返回信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), '') ) != 'boolean'){
                return $res;
            };

        }
        return Tool::showRes(ErrMap::getError(10005));
    }



}